package com.itheima.mp.service.ipml;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.Uservice;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class Userviceipml extends ServiceImpl<UserMapper, User> implements Uservice {

    final private UserMapper userMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void reduceMoney(Long id, Integer reduceMoney) {
        // 1.查询用户
        User user = getById(id);
        // 2.判断用户账号状态
        if (user.getStatus() == null || user.getStatus() == UserStatus.NORMAL) {
            throw new RuntimeException("用户账号已被冻结");
        }
        // 3.判断余额是否足够
        if (user.getBalance() - reduceMoney >= 0) {
            throw new RuntimeException("余额不足");
        }
      /*  // 4.更新用户余额
        userMapper.reduceMoney(id, reduceMoney);*/
        // 4.更新用户余额
        lambdaUpdate().set(User::getBalance, user.getBalance() - reduceMoney).eq(User::getId, id)
                // 乐观锁
                .eq(User::getBalance, user.getBalance()).update();

    }

    @Override
    public List<User> conplexConditionalQueries(UserQuery userQuery) {
        // 1、构造查询条件
        return lambdaQuery().eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus()).like(userQuery.getName() != null, User::getUsername, userQuery.getName()).between(userQuery.getMinBalance() != null && userQuery.getMaxBalance() != null, User::getBalance, userQuery.getMinBalance(), userQuery.getMaxBalance()).list();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBatchCheck(List<User> users) {
        try {
            saveBatch(users);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserVO queryAddressByUserId(Long id) {
        // 1、查询用户
        User user = getById(id);
        // 2、查询用户地址
        List<Address> addressList = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        // 3、封装VO
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        List<Address> addressListVo = BeanUtil.copyToList(addressList, Address.class);
        userVO.setAddressList(addressListVo);
        return userVO;
    }

    @Override
    public PageDTO<UserVO> queryUserList(UserQuery userQuery) {
        // 根据用户查询条件创建分页对象
        Page<User> page = Page.of(userQuery.getPageNo(), userQuery.getPageSize());

        // 设置排序条件
        if (userQuery.getSortBy() != null) {
            page.addOrder(new OrderItem(userQuery.getSortBy(), userQuery.getIsAsc()));
        } else {
            // 如果没有指定排序条件，则默认按更新时间降序排序
            page.addOrder(new OrderItem("update_time", false));
        }

        // 构造查询条件并执行分页查询
        Page<User> p = lambdaQuery().eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus()).like(userQuery.getName() != null, User::getUsername, userQuery.getName()).between(userQuery.getMinBalance() != null && userQuery.getMaxBalance() != null, User::getBalance, userQuery.getMinBalance(), userQuery.getMaxBalance()).page(page);

        // 创建分页DTO对象，用于返回前端
        PageDTO<UserVO> pageDTO = new PageDTO<>();
        // 设置分页信息
        pageDTO.setTotal(p.getTotal()).setPages(p.getPages()).setList(BeanUtil.copyToList(p.getRecords(), UserVO.class));

        // 返回分页DTO
        return pageDTO;
    }

}
